//
//  oldLocationManager.m
//  laonianbangSupport
//
//  Created by 勇拓 李 on 17/11/8.
//  Copyright © 2017年 zaiyou. All rights reserved.
//

#import "oldLocationManager.h"
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import "oldNetWork.h"

@implementation oldLocation
@end

@interface oldLocationManager()<BMKGeoCodeSearchDelegate, BMKLocationServiceDelegate>
@property (nonatomic, strong)oldLocation *location;
@property (nonatomic, strong)BMKLocationService *locService;//定位
@property (nonatomic, strong)BMKGeoCodeSearch *geocodesearch; //地理编码主类，用来查询、返回结果信息
@property (nonatomic, assign)BOOL location_once;

@property (nonatomic, strong)NSTimer *timer;

@end

NSString * const oldLocationKey = @"oldLocationKey";

@implementation oldLocationManager

+ ( instancetype ) shareInstance
{
    static oldLocationManager * instance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once( &onceToken, ^
                  {
                      instance = [self new];
                  });
    return instance;
}

- ( id ) init
{
    if( self = [super init] )
    {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:oldLocationKey]) {
            _location = [[oldLocation alloc] initWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:oldLocationKey]];
        }
        //初始化BMKLocationService
        
        _locService = [[BMKLocationService alloc]init];
        
        _locService.delegate = self;
        _locService.distanceFilter = 100.f;
        _locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        
        _geocodesearch = [[BMKGeoCodeSearch alloc] init];
        
        _geocodesearch.delegate = self;
    }
    return self;
}

- (oldLocation *)getLocation
{
    return self.location;
}


- (void)locationOneTime
{
    _location_once = YES;
    [self startLocation];
}

//开始定位

-(void)startLocation
{
    //启动LocationService
    
    [_locService startUserLocationService];
}

- (void)BMKSearch:(CLLocationCoordinate2D)pt
{
    //构造AMapReGeocodeSearchRequest对象
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    //发起逆地理编码
    [_geocodesearch reverseGeoCode:reverseGeoCodeSearchOption];
}

- (void)stopLocation
{
    [_locService stopUserLocationService];
}

- (void)startUpLoadGeo
{
    self.timer = [NSTimer timerWithTimeInterval:60.f target:self selector:@selector(uploadLocation) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self uploadLocation];
}

- (void)uploadLocation
{
    if (_location.lat && _location.lng) {
        
        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:_location.lat, @"lat", _location.lng, @"lng", nil];
        if (_location.address) {
            [param setValue:_location.address forKey:@"location"];
        }
        
        [OLDNetWork httpRequestWithPostPut:URL_SendGeo params:param success:^(NSDictionary *dic) {
            
        } error:^(NSString *error) {
            
        }];
    }
}

- (void)cancelUpLoadGeo
{
    if (self.timer) {
        if ([self.timer isValid]) {
            [self.timer invalidate];
        }
        self.timer = nil;
    }
}

#pragma mark - delegate
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    
    NSLog(@"heading is %@",userLocation.heading);
    
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    _location = [[oldLocation alloc] init];
    _location.lat = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.latitude];
    _location.lng = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.longitude];
    NSDictionary *dic = [_location covertToDictionary];
    [[NSUserDefaults standardUserDefaults] setObject:dic forKey:oldLocationKey];
    
    CLLocationCoordinate2D pt = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    
    [self BMKSearch:pt];
    
    if (_location_once) {
        [_locService stopUserLocationService];
        _location_once = NO;
        [self uploadLocation];
    }
}

#pragma mark -------------地理反编码的delegate---------------

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error

{
    
    NSLog(@"address:%@----%@",result.addressDetail,result.address);
    
    
    _location.address = result.address;
    
    NSDictionary *dic = [_location covertToDictionary];
    [[NSUserDefaults standardUserDefaults] setObject:dic forKey:oldLocationKey];
    
    //addressDetail:     层次化地址信息
    
    //address:    地址名称
    
    //businessCircle:  商圈名称
    
    // location:  地址坐标
    
    //  poiList:   地址周边POI信息，成员类型为BMKPoiInfo
    
}

//定位失败

- (void)didFailToLocateUserWithError:(NSError *)error{
    
    NSLog(@"error:%@",error);
    
}

@end
